package net.butfly.albacore.helper.async;

import java.util.HashMap;
import java.util.Map;

import net.butfly.albacore.helper.AsyncHelper;
import net.butfly.albacore.helper.HelperBase;
import net.butfly.albacore.helper.async.TaskExecutorFactory.ExecutorMode;

import org.springframework.core.task.AsyncTaskExecutor;
import org.springframework.scheduling.SchedulingTaskExecutor;

public class AsyncHelperSpringImpl extends HelperBase implements AsyncHelper {
	private static final long serialVersionUID = -1372378392364218536L;
	private long startTimeout = AsyncTaskExecutor.TIMEOUT_INDEFINITE;
	private SchedulingTaskExecutor executor = null;
	private ExecutorMode mode = ExecutorMode.CONCURRENT;
	private Map<String, Object> params = new HashMap<String, Object>();

	public void setCorePoolSize(int corePoolSize) {
		this.params.put("corePoolSize", corePoolSize);
	}

	public Thread execute(AsyncTaskBase task) throws AsyncTaskException {
		if (null == this.executor) this.executor = TaskExecutorFactory.getExecutor(this.mode, params);
		Thread t = new RunnableTask(task);
		this.executor.execute(t, this.startTimeout);
		return t;
	}

	public void setMode(ExecutorMode mode) {
		this.mode = mode;
	}

	public void setStartTimeout(long startTimeout) {
		this.startTimeout = startTimeout;
	}
}
